import Taro from '@tarojs/taro'
import { View,Form,Input,Button} from '@tarojs/components'
import { AtForm,} from 'taro-ui'
import {useEffect, useState} from 'react'
import { loginVerification,loginByPhone } from '../../api/mode'
import './index.scss'


export default function TelLogin(){
  const [tel,setTel]=useState()
  const [verificationCode,setVerificationCode]=useState()
  const [showButton,setshowButton]=useState(false)
  const [count,setCount]=useState(60)
  const [buttonContent,setButtonContent]=useState('获取验证码')
//   const [countDownInfo, setCountDownInfo] = useState({
//     code_ts: '获取验证码',
//     show_btn: true,
//     count: 3,
// })


let timer=null
useEffect(() => {
  clearInterval(timer);
  return () => clearInterval(timer);
}, []);

useEffect(() => {
  if (count > 0 && count < 60) {
    setButtonContent(`${count}s后重发`);
  } else {
    clearInterval(timer);
    setshowButton(false);
    setCount(60);
    setButtonContent('获取验证码');
  }
}, [count]);

//点击登录事件
  const onSubmit= ()=> {
    const value={phone:`${tel}`,verificationCode:`${verificationCode}`}
    loginByPhone(value).then(
      res=>{
    if(res.data.code===600){
      Taro.setStorageSync('auth',res.data.data.token)//存储jwt密钥
      Taro.setStorageSync('openid',res.data.data.openid)//存储openid
      console.log('登录成功');
      Taro.reLaunch({
        url: `/pages/index/index`,
      })    
    }else if (res.data.code===602){
      console.log('验证码错误');
      Taro.showToast({
        title:'验证码错误',
        icon:'error',
        duration:1500
      })
    }
      }
    )
    
  }


  //点击获取验证码事件
  const getCode=()=>{
    if(tel==='' || !(/^1[3456789]\d{9}$/.test(tel))){
      console.log('提示信息')
      Taro.showToast(
      {
        title:'手机号格式错误',
        icon:'error'
      }
      )
    }
    else{
      // 这里写一个定时器就可以去更新灰色按钮的内容而且show_btn是false时会出现灰色按钮，当倒计时结束又变成可以触发的按钮
        timer = setInterval(() => setCount(t => --t), 1000);
        setshowButton(true)//当倒计时结束时清除计时器后才会触发
    }

    // 获取短信验证码
 loginVerification(tel).then(
      res=>{
        console.log(res.data);
        if(res.data.message==="没有对应信息,请先注册!"){
          console.log('去注册');
          Taro.redirectTo({
            url:'/pages/register/register'
          })
        }
      }
    )
  }

 
  const jumpToRegister=()=>{
    Taro.redirectTo(
      {
        url:'/pages/telRegisterCheck/telRegisterCheck'
      }
    )
  } 


  return(
    <View className='AccountLogin'> 
        <AtForm
          onSubmit={onSubmit}
        >
           <Input 
             className='telInput'
             name='tel'  
             type='text' 
             placeholder='手机号' 
             value={tel} 
             onInput={(e)=>
            {setTel(e.detail.value)
            // console.log(`account:${e.detail.value}`)
          }}
           />

{/* 手机验证码 */}
            <View className='at-row'>
            <Input 
              className='codeInput at-col at-col-6'
              name='verificationCode'  
              type='text' 
              placeholder='验证码' 
              value={verificationCode} 
              onInput={(e)=>{
              setVerificationCode(e.detail.value);
              // console.log(`password:${e.detail.value}`)
            }}
            />


            <View className='at-col at-col-6 '>
              {
                showButton
                ?
                <Button className='getCodeButton' >
                {buttonContent}
                </Button>
                :              
                 <Button className='getCodeButton' onClick={getCode}>
                  获取验证码
                </Button>
  
              }
            </View>

            </View>
           
              <View className='registerHint' onClick={jumpToRegister}>
                没有账号？立即注册
              </View>


          <Button
            className='telLoginButton'
            formType='submit'
          >
        登录
      </Button>
      </AtForm>

    </View>
  )
}